<template>
  <div class="basket">
    <p v-if="!list.length">暂无菜单</p>

    <ul class="menu-list">
      <li
        v-for="(d, i) in list"
        :key="d.name"
      >
        <h4>{{ d.name }}</h4>
        <div class="btn-list">
          <button @click="showItemModal(i)">+添加用料</button>
          <button @click="list.splice(i, 1)">删除这个清单</button>
        </div>

        <!-- todo：这里需要组件 -->
        <item-list
          :list="d.items"
          @toggle="toggle(i, $event)"
        />

      </li>
    </ul>

    <button class="add" @click="show.menu = true">+</button>

    <menu-modal
      :show="show.menu"
      @close="show.menu = false"
      @add-menu="addMenu"
    ></menu-modal>
    <item-modal
      :show="show.item"
      @close="show.item = false"
      @add-item="addItem"
      :menu-name="(list[activeIndex] || {}).name || ''"
    ></item-modal>
  </div>
</template>

<script>
import { getVal, setVal } from './storage';
import MenuModal from "./MenuModal.vue";
import ItemModal from "./ItemModal.vue";
import ItemList from "./ItemList.vue";
export default {
  components: { MenuModal, ItemModal, ItemList },
  data() {
    return {
      list:  getVal(),
      show: {
        menu: false,
        item: false,
      },
      activeIndex: -1
    };
  },
  watch: {
    list: {
      deep: true,
      handler(arr) {
        setVal(arr);
      }
    }
  },
  methods: {
    // i菜的下标，j配料的下标
    toggle(i, name) {
      const j = this.list[i].items.findIndex(item => item.name === name);
      this.list[i].items[j].done = !this.list[i].items[j].done;
    },
    showItemModal(index) {
      this.activeIndex = index;
      this.show.item = true;
    },
    addMenu(name) {
      this.list.push({
        name,
        items: [],
      })
      this.show.menu = false;
    },
    addItem(dt) {
      this.list[this.activeIndex].items.push({...dt, done: false});
      this.show.item = false;
    }
  }
};
</script>

<style lang="sass">
.basket
  width: 400px
  height: 500px
  margin: 0 auto
  background: #f0f0f0
  border: 1px solid #999
  position: relative
  padding: 20px
  .add
    position: absolute
    bottom: 30px
    right: 30px
    border-radius: 50%
    width: 40px
    height: 40px
    background: #ff9900
    color: #fff
    font-size: 28px
    text-align: center
  .btn-list button
    margin-right: 10px
    border: 1px solid #ccc
    border-radius: 3px
    padding: 2px 5px
</style>
